const app = getApp();
let cacheTreeDate = [];
let cachePicTreeDate = [];
let cacheBankTreeDate = [];
let cacheTargetIdMap = new Map();
let node = {
  id: "",
  name: "",
  selectedType: "",
  treeId: "",
  isLoaded: false,
  isOrg: true,
  open: false,
  children: [],
};
Page({
  data: {
    halfChoseArr: [], //半选中数据
    targetClassify: "",
    currentTab: 1, //student
    isDisableTab: false, //控制是否禁用tab切换
    choseArr: [],
    choseArrCN: [],
    coachingTargetUserIds: [],
    coachingSessionId: "",
    treedata: [],
    bankdata: [], //银行
    picdata: [], //太平洋
    dataTree: [],
    selectItem: {}, //选中的节点id
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    console.log(app.globalData, "globalData");
    // this.getMenuBtnList(tree)
  },
  onShow() {
    let currentTab =
      app.globalData.targetClassify &&
      app.globalData.targetClassify !== "student"
        ? 2
        : 1;
    let coachingSessionId =
      app.globalData.coachingSessionId || "1849242289428234240";
    this.data.coachingSessionId = coachingSessionId;
    this.data.targetClassify = app.globalData.targetClassify || "student";
    this.data.coachingTargetUserIds =
      app.globalData.coachingTargetUserIds || [];

    cacheTargetIdMap.clear();

    this.data.coachingTargetUserIds.forEach((item) => {
      let type = item.nodeData && item.nodeData === "semiTarget" ? 2 : 1;
      cacheTargetIdMap.set(item.targetId, type);
    });

    this.setData({
      currentTab: currentTab,
    });

    this.treeGet(currentTab);
  },
  //获取树
  treeGet(currentTab) {
    this.data.isDisableTab = true;
    if(currentTab ===1){
      this.getBankTree(() => {
        this.data.isDisableTab = false;
      });
    }else{
      this.getPicTree(() => {
        this.data.isDisableTab = false;
      });
    }
  },
  //数据反显
  treeDataDisplay() {},
  handleSelect(e) {
    this.treeSelectDeal(e.detail.selectItem);
  },
  handleTreeOpen(e) {
    this.treeOpenDeal(e.detail.openItem);
  },
  async treeOpenDeal(value) {
    let treeIdArry = value.treeId.split("-");
    //获取渲染树子节点
    let selecteItem = this.getTreeItem(this.data.dataTree, treeIdArry);
    //selecteItem.open = !selecteItem.open;
    //获取缓存树子节点
    let selecteItemCache = this.getTreeItem(cacheTreeDate, treeIdArry);
    if (selecteItemCache.isLoaded === true) {
      selecteItem.children = JSON.parse(
        JSON.stringify(selecteItemCache.children)
      );
      selecteItem.isLoaded = true;
      selecteItem.open = !selecteItem.open;
    } else {
      let isManualSelect = cacheTargetIdMap.get(selecteItem.id) === undefined;
      selecteItem.children = await this.getTreeNodeData(
        value.id,
        value.treeId + "-",
        selecteItem.selectedType === 2 ? 0 : selecteItem.selectedType, //2 是被动类型，不可向下传递
        isManualSelect
      );
      selecteItem.isLoaded = true;
      selecteItem.open = !selecteItem.open;
      //放入缓存树
      selecteItemCache.children = JSON.parse(
        JSON.stringify(selecteItem.children)
      );
      selecteItemCache.isLoaded = true;
    }
    this.setData({ dataTree: this.data.dataTree });
  },
  //API获取子树数据
  async getTreeNodeData(id, treeId, selectedType, isManualSelect) {
    let url =
      this.data.currentTab === 2
        ? "cpic_internal_org_getTreeWithUserByParentId"
        : "cpic_org_getTreeWithUserByParentId";
    let res = await app.api.get({
      url: url,
      data: { orgId: id },
    });
    return new Promise((resolve, reject) => {
      resolve(
        this.treeNodeResponseDataDeal(
          res[0],
          treeId,
          selectedType,
          isManualSelect
        )
      );
    });
  },
  //对返回的子树数据进行处理
  treeNodeResponseDataDeal(data, treeId, selectedType, isManualSelect) {
    let children = [];
    let index = 0;
    data.childs.forEach((item) => {
      let mapType = cacheTargetIdMap.get(item.id); //从map获取节点类型
      let resultType = isManualSelect
        ? selectedType
        : typeof mapType === "number"
        ? mapType
        : selectedType;
      if (isManualSelect) {
        cacheTargetIdMap.delete(item.id);
      }
      let obj = {
        id: item.id,
        name: item.orgName,
        selectedType: resultType,
        treeId: treeId + index,
        isLoaded: false,
        isOrg: true,
        open: false,
        hasOrgPermission:item.hasOrgPermission,
        childrenNumb: item.childNum,
        children: [],
      };
      children.push(obj);
      //更新index
      index += 1;
    });
    data.users.forEach((item) => {
      let mapType = cacheTargetIdMap.get(item.id); //从map获取节点类型
      let resultType = isManualSelect
        ? selectedType
        : typeof mapType === "number"
        ? mapType
        : selectedType;
      if (isManualSelect) {
        cacheTargetIdMap.delete(item.id);
      }
      let obj = {
        id: item.id,
        name: item.realName,
        selectedType: resultType,
        treeId: treeId + index,
        isLoaded: false,
        isOrg: false,
        open: false,
        childrenNumb: 0,
        hasOrgPermission:data.hasOrgPermission,
        children: [],
      };
      children.push(obj);
      //更新index
      index += 1;
    });
    return children;
  },
  //树选择后处理数据
  treeSelectDeal(value) {
    let treeIdArry = value.treeId.split("-");
    //修改选择节点数据
    let selecteItem = this.getTreeItem(this.data.dataTree, treeIdArry);
    const selectedType =
      selecteItem.selectedType === 0 || selecteItem.selectedType === 2 ? 1 : 0;
    selecteItem.selectedType = selectedType;
    cacheTargetIdMap.delete(selecteItem.id);
    this.setTreeItem(selecteItem, "selectedType", selectedType);
    this.calculateTreeItemSelectNumb(this.data.dataTree, treeIdArry);
    cacheTreeDate = this.data.dataTree;
    this.setData({ dataTree: this.data.dataTree });
  },

  getTreeItem(treeData, treeIdArry) {
    let index = treeIdArry.slice(0, 1);
    let newTreeIdArry = treeIdArry.slice(1);
    if (treeIdArry.length <= 1) {
      return treeData[treeIdArry];
    }
    return this.getTreeItem(treeData[index].children, newTreeIdArry);
  },
  setTreeItem(item, key, value) {
    if (item.children && item.children.length > 0) {
      item.children.forEach((innerItem, index) => {
        item.children[index][key] = value;
        if (key === "selectedType") {
          cacheTargetIdMap.delete(item.children[index].id);
        }
        this.setTreeItem(item.children[index], key, value);
      });
    } else {
      item[key] = value;
      if (key === "selectedType") {
        cacheTargetIdMap.delete(item.id);
      }
    }
  },
  calculateTreeItemSelectNumb(treeData, treeIdArry) {
    let index = treeIdArry.slice(0, 1);
    let newTreeIdArry = treeIdArry.slice(1);
    let treeNode = treeData[index];
    let treeChild = treeData[index].children;
    if (treeChild && treeChild.length >= 1) {
      let typeOne = 0;
      let typeTwo = 0;
      treeChild.forEach((item, innerIndex) => {
        if (
          newTreeIdArry.length > 1 &&
          item.children &&
          item.children.length >= 1
        ) {
          this.calculateTreeItemSelectNumb(treeChild, newTreeIdArry);
        }
        if (item.selectedType === 1) typeOne++;
        else if (item.selectedType === 2) typeTwo++;
      });
      if (typeOne === treeChild.length) {
        treeNode.selectedType = 1;
      } else if ((typeOne !== treeChild.length && typeOne > 0) || typeTwo > 0) {
        //注意条件
        treeNode.selectedType = 2;
      } else {
        treeNode.selectedType = 0;
      }
      cacheTargetIdMap.delete(treeNode.id);
    }
  },
  //根树处理
  originTreeDataDeal(data) {
    if (!(data && data instanceof Array && data.length > 0)) return;
    let newArry = [];
    let index = 0;
    data.forEach((item) => {
      let mapType = cacheTargetIdMap.get(item.id); //从map获取节点类型
      let obj = {
        id: item.id,
        name: "",
        selectedType: mapType === undefined ? 0 : mapType,
        treeId: index + "",
        isLoaded: false,
        isOrg: false,
        open: false,
        childrenNumb: item.childNum,
        hasOrgPermission:item.hasOrgPermission,
        children: [],
      };
      if (item.orgName) {
        obj.name = item.orgName;
        obj.isOrg = true;
        newArry.push(obj);
      } else if (item.realName) {
        obj.name = item.realName;
        obj.isOrg = false;
        newArry.push(obj);
      }

      //更新index
      index += 1;
    });
    return newArry;
  },
  //获取银行组织二级架构
  async getBankTree(callback) {
    let res = await app.api.post({
      url: "cpic_org_getOrgsByDepth",
      data: { depth: 2 },
    });
    let newBankDate = this.originTreeDataDeal(res);
    this.setData({
      dataTree: newBankDate,
    });
    cacheTreeDate = JSON.parse(JSON.stringify(newBankDate));
    if (callback && callback instanceof Function) {
      callback();
    }
  },
  //获取太保组织二级架构
  async getPicTree(callback) {
    //获取第一级，根据返回数据获取其id
    let depthRes = await app.api.post({
      url: "cpic_internal_org_getOrgsByDepth",
      data: { depth: 1 },
    });
    if (!(depthRes && depthRes instanceof Array && depthRes.length > 0)) return;
    //根据id获取相应的组织和用户
    let res = await app.api.get({
      url: "cpic_internal_org_getTreeWithUserByParentId",
      data: { orgId: depthRes[0].id },
    });
    let newBankDate = this.treeNodeResponseDataDeal(res[0], "", 0);
    this.setData({
      dataTree: newBankDate,
    });
    cacheTreeDate = JSON.parse(JSON.stringify(newBankDate));
    if (callback && callback instanceof Function) {
      callback();
    }
  },
  //获取所有选中的数据
  getTreeSelectedData(tree) {
    let selectedData = [];
    function getData(data) {
      if (data && data instanceof Array) {
        data.forEach((item) => {
          if (
            item.children &&
            item.children instanceof Array &&
            item.children.length > 0
          ) {
            getData(item.children);
          }
          if (item.selectedType === 1 || item.selectedType === 2) {
            selectedData.push({
              id: item.id,
              name: item.name,
              treeId: item.treeId,
              isOrg: item.isOrg,
              selectedType: item.selectedType,
            });
          }
        });
      }
    }

    getData(tree);

    return selectedData;
  },
  //处理勾选的数据，传出
  getLastTreeSelectData(value) {
    let choseArr = [];
    let choseArrCN = [];
    let targetClassify =
      this.data.targetClassify === "student" ? "bankOrg" : "cpicOrg";

    value.forEach((item) => {
      let tempObj = {
        targetId: item.id,
        targetClassify: item.isOrg ? targetClassify : "user",
      };
      if (item.selectedType === 1) {
        choseArr.push(tempObj);
        choseArrCN.push(item.name);
      } else if (item.selectedType === 2) {
        Object.assign(tempObj, { nodeData: "semiTarget" });
        choseArr.push(tempObj); //不需要反显到选中的数据
      }
    });
    app.globalData.coachingTargetUserIds = choseArr;
    app.globalData.coachingTargetUserIdsCN = choseArrCN;
    app.globalData.targetClassify = this.data.targetClassify;
  },
  //点击切换
  clickTab: function (e) {
    if (
      this.data.currentTab === e.target.dataset.current ||
      this.data.isDisableTab === true
    ) {
      return;
    } else {
      let tree = this.data.dataTree;
      let currentTab = this.data.currentTab;
      let newTab = "";
      //切换树组织
      console.log("currentTab", currentTab);
      if (currentTab === 1) {
        this.data.bankdata = tree;
        this.data.targetClassify = "admin";
        newTab = 2;
        cacheBankTreeDate = cacheTreeDate;
      } else {
        this.data.picdata = tree;
        this.data.targetClassify = "student";
        newTab = 1;
        cachePicTreeDate = cacheTreeDate;
      }
      cacheTreeDate = currentTab === 1 ? cachePicTreeDate : cacheBankTreeDate;
      this.setData({
        dataTree: currentTab === 1 ? this.data.picdata : this.data.bankdata,
        currentTab: newTab,
      });

      //如果没有加载太保组织架构
      if (cachePicTreeDate.length <= 0) {
        this.data.isDisableTab = true;
        this.getPicTree(() => {
          this.data.isDisableTab = false;
        });
      }
      if(cacheBankTreeDate.length <= 0) {
        this.data.isDisableTab = true;
        this.getBankTree(() => {
          this.data.isDisableTab = false;
        })
      }

    }
  },
  //确定按钮
  listSumbit() {
    //获取选择的数据
    this.getLastTreeSelectData(this.getTreeSelectedData(this.data.dataTree));
    app.globalData.dataUpdata = "pending";
    wx.navigateBack();
    // wx.navigateTo({
    //   url: '/myself/pages/train-manage/courseschose/courseschose'
    // })
  },
});
